package com.web.pachong.controller;

import com.alibaba.fastjson.JSONArray;
import com.common.core.exception.PlatformException;
import com.common.core.utils.CopyUtil;
import com.common.core.utils.JsonUtil;
import com.common.core.utils.ReType;
import com.domain.bean.sys.SysMenu;
import com.domain.bean.sys.SysRole;
import com.domain.bean.sys.SysUser;
import com.domain.bean.dto.SysRoleVO;
import com.pachong.common.BaseController;
import com.pachong.service.SysMenuService;
import com.pachong.service.SysRoleService;
import com.web.pachong.core.annotation.Log;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author zhuxiaomeng
 * @date 2017/12/19.
 * @email 154040976@qq.com
 * 角色业务
 */
@Controller
@RequestMapping(value = "/role")
public class RoleController extends BaseController {

  @Autowired
  private SysRoleService roleService;

  @Autowired
  private SysMenuService menuService;

  @GetMapping(value = "showRole")
  @RequiresPermissions(value = "role:show")
  public String showRole(){
    return "/system/role/roleList";
  }

  @ApiOperation(value = "/showRoleList", httpMethod = "GET", notes = "展示角色")
  @GetMapping(value = "showRoleList")
  @ResponseBody
  @RequiresPermissions("role:show")
  public String showRoleList(SysRole role, String page, String limit){
    ReType<SysRole> show = roleService.show(role, Integer.valueOf(page), Integer.valueOf(limit));
    List<SysRoleVO> sysRoleVOS = CopyUtil.copyList(show.getData(), SysRoleVO.class);
    ReType<SysRoleVO> shouwReType = new ReType<SysRoleVO>(show.getCount(),sysRoleVOS);
    String s = JsonUtil.toJson(shouwReType);
    return s;
  }

  @GetMapping(value = "showAddRole")
  public String addRole(Model model) {
    JSONArray jsonArray=menuService.getTreeUtil(null);
    String s = jsonArray.toJSONString();
    System.err.println("---:"+s);
    model.addAttribute("menus",jsonArray.toJSONString());
    return "/system/role/add-role";
  }

  @ApiOperation(value = "/addRole", httpMethod = "POST", notes = "添加角色")
  @Log(desc = "添加角色")
  @PostMapping(value = "addRole")
  @ResponseBody
  public String addRole(SysRole sysRole,String[] menuIds){
    if(StringUtils.isEmpty(sysRole.getRoleName())){
      return "角色名称不能为空";
    }
    try{
      Set<SysMenu> sysMenus = sysRole.getMenus();
      this.getMenus(menuIds,sysMenus);
      roleService.save(sysRole);
    }catch (PlatformException e){
      e.printStackTrace();
    }
    return "保存成功";
  }

  @GetMapping(value = "updateRole")
  public String updateRole(String id, Model model, boolean detail){
    if (StringUtils.isBlank(id)) {
      model.addAttribute("detail", detail);
      return "system/role/update-role";
    }

    SysRole role = roleService.selectByPrimaryKey(id);
    model.addAttribute("role", role);
    JSONArray jsonArray=menuService.getTreeUtil(id);
    model.addAttribute("menus",jsonArray.toJSONString());
    System.err.println("查询到的菜单："+jsonArray.toJSONString());
    model.addAttribute("detail", detail);
    return "system/role/update-role";
  }

  @ApiOperation(value = "/updateRole", httpMethod = "POST", notes = "更新角色")
  @Log(desc = "更新角色")
  @PostMapping(value = "updateRole")
  @ResponseBody
  public JsonUtil updateUser(SysRole role, String[] menus) {
    JsonUtil jsonUtil = new JsonUtil();
    jsonUtil.setFlag(false);
    if (role == null) {
      jsonUtil.setMsg("获取数据失败");
      return jsonUtil;
    }

    try {
      SysRole oldRole = roleService.selectByPrimaryKey(role.getId());
      Set<SysMenu> sysMenus = new HashSet<>();
      this.getMenus(menus,sysMenus);
      oldRole.setMenus(sysMenus);
      roleService.saveAndFlush(oldRole);
      jsonUtil.setFlag(true);
      jsonUtil.setMsg("修改成功");
    } catch (PlatformException e) {
      e.printStackTrace();
    }
    return jsonUtil;
  }

  /**
   * 把菜单的IDs转换成对象Set集合
   * @param menuIds
   * @param sysMenus
   */
  private void getMenus(String[] menuIds,Set<SysMenu> sysMenus){
    if(menuIds != null)
      for(String menuId:menuIds){
        SysMenu sysMenu = new SysMenu();
        sysMenu.setId(menuId);
        sysMenus.add(sysMenu);
      }
  }

  @ApiOperation(value = "/del", httpMethod = "POST", notes = "删除角色")
  @Log(desc = "删除角色",type = Log.LOG_TYPE.DEL)
  @PostMapping(value = "del")
  @ResponseBody
  public String del(String id) {
    if (StringUtils.isEmpty(id)) {
      return "获取数据失败";
    }
    try {

      SysRole role = roleService.selectByPrimaryKey(id);
      Set<SysUser> users = role.getUsers();
      if(users != null && !users.isEmpty()){
        return "已分配给用户，删除失败";
      }

      roleService.deleteByPrimaryKey(id);
    } catch (PlatformException e) {
      e.printStackTrace();
    }
    return "删除成功";
  }

}
